//
//  PasswordViewController.m
//  网络
//
//  Created by hfzhangzhang on 2018/4/10.
//  Copyright © 2018年 hfzhangzhang. All rights reserved.
//

#import "PasswordViewController.h"
#import "NSString+Hash.h"
#import "SSKeychain.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "EncryptionTools.h"
#import "RSACryptor.h"


/* 盐*/
static NSString * salt = @"lkajsd;flj)(*@$!#(*&OJKD(*&)291IOJPOIHCD*FUPOH$RO*UOIDSHFP(*EWUJRT:LK@#$U(*)_Q#R()IJD*(F_U";


#define HKLoginServiceName @"HKLoginServiceName"

@interface PasswordViewController ()
@property (weak, nonatomic) UITextField *UserText;
@property (weak, nonatomic) UITextField *PwdText;
@end

@implementation PasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加载用户信息
    [self loadUserInfo];
    
}
- (void)login:(id)sender {
    //发请求给服务器 -- 验证
    NSString * user = self.UserText.text;
    //密码 明文的!!
    NSString * pwd = self.PwdText.text;
    // 1. ------------- MD5 加密 --------------
    //    pwd = pwd.md5String;
    // 2. ------------- MD5 加盐 --------------
    //不足:盐是固定的!有人知道!!
    //    pwd = [pwd stringByAppendingString:salt].md5String;
    // 3. ------------- HMAC --------------
    // 在实际开发中,密钥来自于服务器!! 注册的时候!!
    NSString * key = nil;//通过钥匙串访问来获取这个key
    if (key == nil) {
        //1.发送网络请求!获取密钥!!
        //2.展示"小菊花!!!"
        key = [self getKeyWithAccunt:user];
        //展示等待授权页面!!
        
        //立刻马上保存这个KEY在本地!! -- 通过钥匙串访问!
        
    }
    pwd = [pwd hmacMD5StringWithKey:key];
    
    
    NSLog(@"现在的密码是:%@",pwd);
    
    //模拟网络请求!!
    if( [self isLoginWithUserId:user PassWord:pwd]){
        //保存账号密码 明文账号--密码
        [self savePwdWithAccunt:self.UserText.text Pwd:self.PwdText.text];
        NSLog(@"登录成功");
    }else{
        NSLog(@"登录失败");
    }
    
}

//加载本地用户信息
-(void)loadUserInfo{
    //加载账号
    self.UserText.text = [[NSUserDefaults standardUserDefaults] stringForKey:@"HKLoginUserName"];
    //找出所有的账号
    self.PwdText.text = [SSKeychain passwordForService:HKLoginServiceName account:self.UserText.text];
}


//保存账号密码
-(void)savePwdWithAccunt:(NSString *)accunt Pwd:(NSString *)pwd{
    //保存账号
    [[NSUserDefaults standardUserDefaults] setObject:self.UserText.text forKey:@"HKLoginUserName"];
    //同步 -- 立刻马上保存!
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //保存密码
    if (accunt.length > 0 && pwd.length> 0) {
        /**
         *  参数
         *  1. 密码明文
         *  2. 服务,可以随便写,但是他是APP的一个标识,建议用BundleID
         *  3. 账号,用户名
         */
        [SSKeychain setPassword:pwd forService:HKLoginServiceName account:accunt];
    }
}


//获取授权信息 -- 等待设备授权!!
-(NSString *)getKeyWithAccunt:(NSString *)accunt{
    //1.需要授权
    //2.直接返回密钥
    return @"hank";
}

- (BOOL)isLoginWithUserId:(NSString *)userid PassWord:(NSString *)passw{
    if ([userid isEqualToString:@"hank"] && [passw isEqualToString:@"e9cdab82d48dcd37af7734b6617357e6"]) {
        return YES;
    }else{
        return NO;
    }
    
}


/*  指纹识别的错误信息
 LAErrorAuthenticationFailed    --- 指纹无法识别
 LAErrorUserCancel              --- 用户点击了"取消"
 LAErrorUserFallback            --- 用户点击了"输入密码"
 LAErrorSystemCancel            --- 系统取消,比如激活了其他应用(用户)
 LAErrorPasscodeNotSet          --- 因为设备上没有设置密码
 LAErrorTouchIDNotAvailable     --- 设备没有Touch ID
 LAErrorTouchIDNotEnrolled      --- 因为用户没有输入指纹
 LAErrorTouchIDLockout          --- 多次输入错误,密码锁定
 LAErrorAppCancel               --- 比如电话进来,用户不可控的
 */

- (void)laContext {
    
    LAContext * ctx = [[LAContext alloc]init];
    
    //判断设备是否支持指纹识别
    if ([ctx canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:NULL]) {
        //输入指纹
        [ctx evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"指纹支付" reply:^(BOOL success, NSError * _Nullable error) {
            NSLog(@"%d %@",success,error);
        }];
        
    }else{
        NSLog(@"不支持");
    }
}


//对称加密算法
-(void)encryptDemo{
    //AES - ECB 加密
    NSString * key = @"hk";
    //加密
    NSLog(@"加密: %@",[[EncryptionTools sharedEncryptionTools] encryptString:@"hello" keyString:key iv:nil]);
    //解密
    NSLog(@"解密: %@",[[EncryptionTools sharedEncryptionTools] decryptString:@"cKRPM1ALLG+0q5qCjADoaQ==" keyString:key iv:nil]);
    
    
    
    //AES - CBC 加密
    uint8_t iv[8] = {2,3,4,5,6,7,0,0}; //直接影响加密结果!
    NSData * ivData = [NSData dataWithBytes:iv length:sizeof(iv)];
    
    NSLog(@"CBC加密: %@",[[EncryptionTools sharedEncryptionTools] encryptString:@"hello" keyString:key iv:ivData]);
    
    NSLog(@"CBC解密: %@", [[EncryptionTools sharedEncryptionTools] decryptString:@"+dv/u4juE0WE3S9XSFyibA==" keyString:key iv:ivData]);
    
    //DES - ECB 加密
    [EncryptionTools sharedEncryptionTools].algorithm = kCCAlgorithmDES;
    NSLog(@"DES 加密%@",[[EncryptionTools sharedEncryptionTools] encryptString:@"hello" keyString:key iv:nil]);
    NSLog(@"DES 解密: %@", [[EncryptionTools sharedEncryptionTools] decryptString:@"vTuv8E5AlWQ=" keyString:key iv:nil]);
}

//
-(void)RSA{
    //1.加载公钥
    [[RSACryptor sharedRSACryptor] loadPublicKey:[[NSBundle mainBundle] pathForResource:@"rsacert.der" ofType:nil]];
    //2. 加载私钥 - P12的文件  password : 生成P12 的时候设置的密码
    [[RSACryptor sharedRSACryptor] loadPrivateKey:[[NSBundle mainBundle] pathForResource:@"p.p12" ofType:nil] password:@"123456"];
    
    
    NSData * reault = [[RSACryptor sharedRSACryptor] encryptData:[@"hello" dataUsingEncoding:NSUTF8StringEncoding]];
    //base64 编码
    NSString * base64 = [reault base64EncodedStringWithOptions:0];
    NSLog(@"加密的信息: %@",base64);
    
    //解密
    NSData * jiemi = [[RSACryptor sharedRSACryptor] decryptData:reault];
    NSLog(@"%@",[[NSString alloc]initWithData:jiemi encoding:NSUTF8StringEncoding]);
}

@end
